#!/bin/bash

echo "=== SSO单点登录系统启动脚本 ==="

# 检查Java环境
if ! command -v java &> /dev/null; then
    echo "错误: 未找到Java环境，请先安装JDK 11+"
    exit 1
fi

# 检查Maven环境
if ! command -v mvn &> /dev/null; then
    echo "错误: 未找到Maven环境，请先安装Maven 3.6+"
    exit 1
fi

echo "Java版本: $(java -version 2>&1 | head -n 1)"
echo "Maven版本: $(mvn -version 2>&1 | head -n 1)"

# 编译项目
echo "正在编译项目..."
mvn clean compile -DskipTests

if [ $? -ne 0 ]; then
    echo "编译失败，请检查代码"
    exit 1
fi

echo "编译成功！"

# 检查Docker环境
if command -v docker &> /dev/null && command -v docker-compose &> /dev/null; then
    echo "检测到Docker环境，是否使用Docker启动？(y/n)"
    read -r use_docker
    
    if [[ $use_docker =~ ^[Yy]$ ]]; then
        echo "使用Docker启动服务..."
        docker-compose up -d
        echo "服务启动完成！"
        echo "访问地址:"
        echo "- Nacos控制台: http://localhost:8848/nacos"
        echo "- 网关服务: http://localhost:8080"
        echo "- 认证服务: http://localhost:8081"
        exit 0
    fi
fi

# 手动启动服务
echo "请确保以下服务已启动:"
echo "1. Nacos (端口: 8848)"
echo "2. MySQL (端口: 3306)"
echo "3. Redis (端口: 6379)"

echo "是否继续启动服务？(y/n)"
read -r continue_start

if [[ $continue_start =~ ^[Yy]$ ]]; then
    echo "启动网关服务..."
    cd sso-gateway
    mvn spring-boot:run &
    GATEWAY_PID=$!
    cd ..
    
    echo "启动认证服务..."
    cd sso-auth-service
    mvn spring-boot:run &
    AUTH_PID=$!
    cd ..
    
    echo "服务启动完成！"
    echo "网关服务PID: $GATEWAY_PID"
    echo "认证服务PID: $AUTH_PID"
    echo "访问地址:"
    echo "- 网关服务: http://localhost:8080"
    echo "- 认证服务: http://localhost:8081"
    
    # 等待用户输入退出
    echo "按任意键停止服务..."
    read -r
    kill $GATEWAY_PID $AUTH_PID
    echo "服务已停止"
else
    echo "启动已取消"
fi 